package com.shuqi.bookcontent;

import java.util.List;

import android.content.Context;
import android.text.TextUtils;

import com.shuqi.activity.viewport.CataLogLayout;
import com.shuqi.activity.viewport.CataLogLayout.OnCatalogScanListener;
import com.shuqi.common.Constant;
import com.shuqi.common.utils.BookContentUtils;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SqImageManager;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.model.BookContentModel;
import com.shuqi.model.bean.BookContentInfo;
import com.shuqi.model.bean.BookData;
import com.shuqi.model.bean.ChapterInfo;
import com.shuqi.model.manager.BookCatalogManager;
import com.shuqi.model.manager.BuyBookManager;
import com.shuqi.model.manager.BuyBookManager.BuyChapterInfoInterface;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.BookContentParserBase;
import com.shuqi.model.parse.BookContentParserBase.OnOneChpaterLoadDone;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

public class BookContentLoaderThread extends Thread {
    private static final String TAG = "BookContentLoaderThread";

    private BookContentInfo mBookContentInfo;

    private Context mContext;

    private final BookContentParserBase mBookContentParserBase;

    private BookContentModel mBookContentModel;

    private onBookContentLoaderListener mListener;

    private boolean mIsInit = false;

    /***
     * 产品需求 如果异常状态下延时两秒退出
     */
    private static final int DELAY_THREAD_M = 2 * 1000;

    public interface onBookContentLoaderListener {

        /****
         * 
         * 加载当前页
         * 
         * @param info 传递过来的参数
         * @param curChapter 当前页绘制所需的bookcontentInfo
         * @param lineList 绘制在页面上的数据
         */
        void loadBookContentInfoCompleted();

        void controlBuyButtonIsClick(boolean isClick);

        void hideBuyLoadingDialog();

        void onAutoBuy();

        void onPayCataLogData(BookData catalog, int pageCount);

        void onCataLogScan(CataLogLayout.OnCatalogScanListener listener);

        void onResetPageIndex();

        void onLoadField(BookContentInfo bookContentInfo);

        void onResetBookInfo(boolean isReset);
    }

    public BookContentLoaderThread(Context context, BookContentInfo contentInfo,
            BookContentParserBase bookContentParserBase, boolean isInit) {
        this.mBookContentInfo = contentInfo;
        this.mContext = context;
        this.mBookContentParserBase = bookContentParserBase;
        this.mIsInit = isInit;
    }

    public void setBookContentModel(BookContentModel bookContentModel) {
        this.mBookContentModel = bookContentModel;
    }


    public void run() {
        mBookContentModel.setOptionsEnable(false);
        Log4an.e("yjd", "type=" + mBookContentInfo.getType() + ",mIsInit=" + mIsInit);
        if (mIsInit && mBookContentInfo.getType() == Constant.BOOKTYPE_TXT) {
            notifyCataLogScan(new OnCatalogScanListener() {
                @Override
                public void onScanFinish(List templist) {
                    mBookContentParserBase.getBookCatalogList();
                }
            });
            mBookContentParserBase.getCurInfos(mContext, mBookContentInfo, true,
                    mIsInit ? new OnOneChpaterLoadDone() {
                        @Override
                        public void oneChapterLoadDone(boolean isRefreshUI) {
                            refreshPageView();
                        }
                    } : null);
            refreshPageView();
            mBookContentModel.setOptionsEnable(true);
        } else {
            if (mIsInit)
                notifyCataLogScan(null);
            mBookContentParserBase.getCurInfos(mContext, mBookContentInfo, true,
                    mIsInit ? new OnOneChpaterLoadDone() {

                        @Override
                        public void oneChapterLoadDone(boolean isRefreshUI) {
                            isRefresh = isRefreshUI;
                            if (!isRefreshUI) {
                                refreshPageView();
                            }
                        }
                    } : null);
            if (isRefresh) {
                refreshPageView();
            }
            mBookContentModel.setOptionsEnable(true);
        }
    }

    boolean isRefresh = true;// 7.3.9 判断是否刷新两次UI,由底层返回控制(解决优化阅读UI刷新两次的问题)

    private void refreshPageView() {
        mBookContentInfo.resetPayType();
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_TXT
                || mBookContentInfo.getType() == Constant.BOOKTYPE_BAG
                || mBookContentInfo.getType() == Constant.BOOKTYPE_UMD
                || mBookContentInfo.getType() == Constant.BOOKTYPE_EPUB) {
            if (mBookContentInfo.getCurChapterBytes() == null) {

                delayThread();

                final String errorMessage = mBookContentInfo.getErrorMessage();
                if (TextUtils.isEmpty(errorMessage)) {
                    notifyLoadField(true);
                } else {
                    ToastUtil.showMessage(errorMessage);
                    notifyLoadField(false);
                }
                return;
            }
        } else {
            Log4an.i(TAG,
                    "[exceptionHandling]mBookContentInfo.getCurChapterType() is null="
                            + (mBookContentInfo.getCurChapterType() == null ? true
                                    : mBookContentInfo.getCurChapterType()));
            final int resId =
                    BookContentUtils.exceptionHandling(mBookContentInfo.getCurChapterType());
            if (BookContentUtils.EXCEPTION_HANDLING_RESID_DEFAULT != resId) {

                delayThread();

                ToastUtil.showMessage(mContext.getResources().getString(resId));
                notifyLoadField(false);
                return;
            }
        }

        if (mBookContentInfo.getType() == Constant.BOOKTYPE_PAY
                || mBookContentInfo.getType() == Constant.BOOKTYPE_ORDER_PAY) {
            initPayMode(mBookContentInfo);
        }

        mBookContentInfo.setMarkIndex(mBookContentInfo.getBookmarkByteOffset());
        mBookContentInfo.refreshCurChapterContentLines(mBookContentModel.getBookContentRender(),
                mBookContentInfo.getMarkIndex());

        final int type = mBookContentInfo.getType();

        String name =
                TextUtils.isEmpty(mBookContentInfo.getCurChapterName()) ? mBookContentInfo
                        .getBookname() : mBookContentInfo.getCurChapterName();
        BookContentUtils.resetBookContentModelReadState(mBookContentModel, type,
                mBookContentInfo.isNeedBuy(), mBookContentInfo.getCurChapterType(), name);

        BookContentUtils.calcBookmarkLineIndex(mBookContentInfo);
        if (mListener != null) {
            mListener.loadBookContentInfoCompleted();
        }
        notifyRestBookInfo(true);
        // 下载封面图（主要解决搜索书籍封面未下载的问题）
        SqImageManager.getImageManager().displayImage(mBookContentInfo.getImageUrl(), null,
                SqImageManager.IMG_COVER, R.drawable.book_shelf_local_random_brown);
    }

    private void delayThread() {
        try {
            Thread.sleep(DELAY_THREAD_M);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void initPayMode(BookContentInfo info) {
        BookInfo bookInfo =
                BookInfoDao.getInstance().getBookInfo(null, info.getBookId(), info.getUid());
        final int buyState =
                bookInfo != null ? bookInfo.getBookAutoBuyState() : BookInfo.DEFAULT_NO_AUTO_BUY;
        if (bookInfo != null) {
            if (BookInfo.DEFAULT_NO_AUTO_BUY == buyState || BookInfo.NO_AUTO_BUY == buyState) {
                manualBuy(info);
            } else if (BookInfo.AUTO_BUY == buyState) {
                autoBuy(info.getCurChapterType());
            }
        } else {
            manualBuy(info);
        }
    }

    /***
     * 需要手动购买 但是状态为正常阅读的状态
     * 
     * @param info
     */
    private void manualBuyHasRead(BookContentInfo info) {
        mBookContentInfo.setType(Constant.BOOKTYPE_PAY);
        mBookContentModel.mReadState = BookContentModel.READ_STATE_NORMAL;

        notifyBuyButtonIsClick(false);
    }

    /***
     * 用户未登录
     * 
     * @param info
     */
    private void manuablBuyNoLogin(BookContentInfo info) {
        notifyBuyButtonIsClick(true);

        mBookContentInfo.setType(Constant.BOOKTYPE_ORDER_PAY);
        // addPayCatalogData(info);
        mBookContentModel.setTypeNoLogin(info.getCurChapterName());
    }

    /***
     * 手动购买
     * 
     * @param info
     */
    private void manulBuyNeedBuy(BookContentInfo info) {

        notifyBuyButtonIsClick(true);

        mBookContentInfo.setType(Constant.BOOKTYPE_ORDER_PAY);
        // addPayCatalogData(info);

        if (BookContentUtils.PAY_TYPE_BOOK.equals(info.getCurChapterPayMode())) {// 全本购买
            mBookContentModel.mReadState = BookContentModel.READ_STATE_PAY;
            mBookContentModel.setChapterTitle(info.getCurChapterName());
            StatisticsUtils.onEvent(mContext, StatisticsEventID.BOOKCONTENT_ENTER_NO_BUY_BOOK);
        } else if (BookContentUtils.PAY_TYPE_CHAPTER.equals(info.getCurChapterPayMode())) {
            mBookContentModel.mReadState = BookContentModel.READ_STATE_PAY;
            mBookContentModel.setChapterTitle(info.getCurChapterName());
            mBookContentModel.setIndexBtnTexts(0);
        }
        // resetBookInfo(true);
    }

    /***
     * 手动购买
     * 
     * @param info
     */
    private void manualBuy(BookContentInfo info) {
        Log4an.e("yjd", "【手动购买】getCurChapterType：" + info.getCurChapterType()
                + ",getCurChapterPayMode" + info.getCurChapterPayMode());

        // 正常阅读
        if (BookContentUtils.TYPE_HAS_READ.equals(info.getCurChapterType())) {// 正常阅读
            manualBuyHasRead(info);
            // 用户未登录
        } else if (BookContentUtils.TYPE_NO_LOGIN.equals(info.getCurChapterType())) {// 通过书架进入，未登录
            manuablBuyNoLogin(info);
            // 用户需要购买
        } else if (BookContentUtils.TYPE_NEDD_BUY.equals(info.getCurChapterType())) {
            manulBuyNeedBuy(info);
        }
    }

    /***
     * 自动购买
     * 
     * @param curChapterType
     */
    private void autoBuy(String curChapterType) {
        if (BookContentUtils.TYPE_HAS_READ.equals(curChapterType)) {
            mBookContentInfo.setType(Constant.BOOKTYPE_PAY);
            mBookContentModel.mReadState = BookContentModel.READ_STATE_NORMAL;
            notifyBuyButtonIsClick(false);
        } else {
            notifyAutoBuy();

            Log4an.e("yjd", "【自动购买】bid=" + mBookContentInfo.getBookId() + ",cid="
                    + mBookContentInfo.getCurChapterCid() + ",uid=" + mBookContentInfo.getUid()
                    + ",price=" + mBookContentInfo.getCurChapterPrice());
            BuyBookManager.buyChapterOnline(mContext, mBookContentInfo.getBookId(),
                    mBookContentInfo.getCurChapterCid(), MyAccountManager.getInstance(mContext)
                            .getUserId(), new BuyChapterInfoInterface() {

                        @Override
                        public void onFinish(ChapterInfo info) {
                            Log4an.e("yjd", "返回状态：" + info.getCurChapterType());
                            Log4an.e(
                                    "yjd",
                                    "[返回]bid=" + info.getBookId() + ",update="
                                            + info.getIsUpdateCatalog() + ",price="
                                            + info.getCurChapterPrice() + ",msg=" + info.getMsg());
                            mBookContentInfo.setType(Constant.BOOKTYPE_ORDER_PAY);
                            if (BookContentUtils.TYPE_HAS_READ.equals(info.getCurChapterType())) {
                                // updateChapterCatalog(info);
                            } else if (BookContentUtils.TYPE_NO_LOGIN.equals(info
                                    .getCurChapterType())) {
                                notifyBuyButtonIsClick(true);
                                mBookContentModel.setTypeNoLogin(mBookContentInfo
                                        .getCurChapterName());
                            } else {
                                mBookContentModel.setChapterTitle(mBookContentInfo
                                        .getCurChapterName());
                                mBookContentModel.mReadState = BookContentModel.READ_STATE_DOWNLOAD;
                            }
                            // 无论成功与失败，都要把dialog取消掉吧。
                            notifyHideBuyLoadingDialog();
                        }

                    }, mBookContentInfo.getCurChapterPrice());
        }
    }

    /**
     * 更新目录:0,不更新；1,更新
     * 
     * @remark 购买成功后刷新目录(待调试)
     * @param retrunVal
     */
    private void updateChapterCatalog(ChapterInfo bookInfo) {
        if (bookInfo != null && !TextUtils.isEmpty(bookInfo.getIsUpdateCatalog())) {
            Log4an.i("yjd", "retrunVal=" + bookInfo.getIsUpdateCatalog());
            if ("1".equals(bookInfo.getIsUpdateCatalog())) {
                BookCatalogManager.asyncDownloadCatalog(bookInfo.getBookId(), null,
                        bookInfo.getUid(), BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
            }
        }
    }


    public void setBookContentLoaderListener(onBookContentLoaderListener l) {
        mListener = l;
    }

    private void notifyRestBookInfo(boolean isReset) {
        if (mListener != null)
            mListener.onResetBookInfo(isReset);
    }

    private void notifyLoadField(boolean needToggle) {
        if (mListener != null)
            mListener.onLoadField(needToggle ? mBookContentInfo : null);
    }

    // private void notifyResetPageIndex() {
    // if (mListener != null)
    // mListener.onResetPageIndex();
    // }

    private void notifyAutoBuy() {
        if (mListener != null) {
            mListener.onAutoBuy();
        }
    }

    private void notifyHideBuyLoadingDialog() {
        if (mListener != null) {
            mListener.hideBuyLoadingDialog();
        }
    }

    private void notifyPayCatLogData(BookData catalog, int pageCount) {
        if (mListener != null) {
            mListener.onPayCataLogData(catalog, pageCount);
        }
    }

    private void notifyBuyButtonIsClick(boolean isClick) {
        if (mListener != null)
            mListener.controlBuyButtonIsClick(isClick);
    }

    private void notifyCataLogScan(CataLogLayout.OnCatalogScanListener listener) {
        if (mListener != null)
            mListener.onCataLogScan(listener);
    }

    /***
     * 网络线程加载收费版目录数据
     * 
     * @param info
     */
    // private void addPayCatalogData(final BookContentInfo info) {
    // if (info != null && info.getBookId() != null) {
    // BookData catalog =
    // BookCatalogManager.getCatalogSQByPageIndex(info.getBookId(),
    // mUserInfo.getUserId(), "0", 1, 60);
    // notifyPayCatLogData(catalog, catalog == null ? 0 : catalog.getPageCount());
    // }
    // }
}
